﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _02_Thread_线程基础
{
    public partial class Form1 : Form
    {
        //线程类
        Thread thread = null;

        public Form1()
        {
            InitializeComponent();
            //取消跨线程访问控件限制(创建出的工作线程可以自由访问主线程)
            //Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 启动线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            thread = new Thread(DoWork);//创建线程，默认是前台线程
            //什么是前台线程？什么是后台线程？
            //前台线程：当所有的前台线程都结束时，程序才会退出
            //后台线程：当所有的前台线程都结束时，程序会退出，不管后台线程是否结束
            //程序中应当只有界面线程是前台线程，其他的工作线程都应当是后台线程
            thread.IsBackground = true;//设置thread为后台线程
            thread.Start();
        }
        public void DoWork()
        {
            try
            {
                for (int i = 0; i <= 100; i++)
                {
                    Thread.Sleep(100);//休眠当前所在的线程100ms
                    this.Invoke(new Action(() =>
                    {
                        //更新进度条
                        this.progressBar1.Value = i;
                        this.label2.Text = i.ToString() + "%";
                    }));
                }
            }
            catch (Exception ex) //捕获所有可能的异常
            {
                Console.WriteLine(ex);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.thread.Interrupt();//中断线程,会固定在Thread.Sleep()处抛出异常然后结束线程
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //线程挂起
            thread.Suspend();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //线程唤醒
            thread.Resume();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //线程终止
            thread.Abort();
        }
    }
}
